#include <iostream>
#include <string>
#include <memory>
#include <ctime>
#include "Socket.hpp"
#include "Protocol.hpp"
#include "InetAddr.hpp"

using namespace socket_ns;
using namespace protocol_ns;

void Usage(std::string proc)
{
    std::cout << "Usage:\n\t" << proc << " serverip serverport\n"
              << std::endl;
}

// ./tcp_client serverip serverport
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(1);
    }
    std::string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);
    InetAddr serveraddr(serverip, serverport);
    std::unique_ptr<Socket> clientsock = std::make_unique<TcpSocket>();
    bool res = clientsock->BulidClientSocket(serveraddr);

    std::string inbuffer;
    while (res)
    {
        sleep(1);
        // 1.创建请求
        Factory factory;
        std::shared_ptr<Request> req = factory.BuildRequest();

        // 2.序列化请求
        std::string send_str;
        req->Serialize(&send_str);
        std::cout << "Serialize: \n"
                  << send_str << std::endl;

        // 3.协议化 发送
        send_str = Encode(send_str);
        std::cout << "Encode: \n"
                  << send_str << std::endl;
        clientsock->Send(send_str);

        // 4.获取应答
        int n = clientsock->Recv(&inbuffer);
        if (n <= 0)
        {
            std::cerr << "server quit" << std::endl;
            break;
        }
        // 保证是package完整的应答
        std::string package = Decode(inbuffer);
        if (package.empty())
            continue;

        // 5.反序列化
        std::shared_ptr<Response> resp = factory.BuileResponse();
        resp->Deserialize(package);
        std::cout << resp->_result << '[' << resp->_code << ']' << std::endl;
        std::cout << "-----------------------" << std::endl;
    }
}